package com.atguigu.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     * PostConstruct 对象构造器创建完成之后，执行
     */
    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 当前消息的唯一关联数据（这个是消息的唯一id）
             * @param ack 消息是否成功收到
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                /**
                 * 1、做好消息确认机制（publisher,comsumer[手动ack]）
                 * 2、每一个发送的消息都在数据库做好记录，定期将失败的消息再次发送一遍
                 */
                //服务器收到了消息
//                System.out.println("confirm..correlationData【" +correlationData + "】");
//                System.out.println("confirm..ack【" +ack + "】");
//                System.out.println("confirm..cause【" +cause + "】");
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//                //投递失败的消息的详细信息
//                System.out.println("return..message[" + message+ "]");
//                //回复码
//                System.out.println("return..replyCode[" + replyCode+ "]");
//                //回复文本
//                System.out.println("return..replyText[" + replyText+ "]");
//                //投递给了哪个交换机
//                System.out.println("return..exchange[" + exchange+ "]");
//                //投递的路由键
//                System.out.println("return..routingKey[" + routingKey+ "]");
            }
        });
    }
}
